package com.ruoyi.web.home.service.impl;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.home.service.IHomeService;
import com.ruoyi.web.invest.asset.asset.domain.Asset;
import com.ruoyi.web.invest.asset.asset.service.IAssetService;
import com.ruoyi.web.operate.stock.domain.Stock;
import com.ruoyi.web.operate.stock.mapper.StockMapper;
import com.ruoyi.web.operate.stock.service.IStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author liuyu
 */
@Service
public class HomeServiceImpl implements IHomeService {

    @Autowired
    private IAssetService iAssetService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private IStockService iStockService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private StockMapper stockMapper;

    /**
     * 获取审核人首页的面板数据
     *
     * @return map
     */
    @Override
    public Map<String, Double> getOperatePanelGroup() {
        Map<String, Double> panelDataMap = new LinkedHashMap<>(4);

        int publisherNum = 0;
        int inverterNum = 0;
        AtomicReference<Long> stockNumReference = new AtomicReference<>(0L);
        AtomicReference<Long> tradNumReference = new AtomicReference<>(0L);


        long publisherId = 100;
        publisherNum = iSysRoleService.countUserRoleByRoleId(publisherId);
        long investorId = 102;
        inverterNum = iSysRoleService.countUserRoleByRoleId(investorId);

        panelDataMap.put("publisherNum", Double.valueOf(publisherNum));
        panelDataMap.put("inverterNum", Double.valueOf(inverterNum));

        iStockService.selectStockList(new Stock()).forEach(stock -> {
            if (null != stock.getAmount()) {
                stockNumReference.updateAndGet(v -> v + stock.getAmount());
            }

            if (null != stock.getVolume()) {
                tradNumReference.updateAndGet(v -> v + stock.getVolume());
            }
        });

        panelDataMap.put("stockNum", Double.valueOf(stockNumReference.get()));
        panelDataMap.put("tradNum", Double.valueOf(tradNumReference.get()));

        return panelDataMap;
    }

    /**
     * 获取投资人首页的面板数据
     *
     * @return map
     */
    @Override
    public Map<String, Double> getInvestPanelGroup() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();

        Map<String, Double> panelDataMap = new LinkedHashMap<>(4);

        int stockNum = 0;

        Stock stockQuery = new Stock();
        stockQuery.setCreateById(user.getUserId());
        List<Stock> stockList = iStockService.selectStockList(stockQuery);
        stockNum = stockList.size();
        panelDataMap.put("stockNum", (double) stockNum);

        AtomicReference<Double> assetSumReference = new AtomicReference<>(0.0);
        List<Asset> assetList = this.iAssetService.selectAssetList(new Asset());
        if (assetList.size() > 0) {
            assetList.forEach(asset -> {
                if (null != asset.getNumber()) {
                    assetSumReference.updateAndGet(v -> v + asset.getNumber());
                }
            });
        }
        panelDataMap.put("assetSum", assetSumReference.get());


        // todo 收益需要计算 总资产+卖出-买入=收益
        panelDataMap.put("earnCount", assetSumReference.get());

        return panelDataMap;
    }

    /**
     * 获取投资人首页的图表数据
     *
     * @return map
     */
    @Override
    public Map<String, String[]> getInvestChartData() {
        Map<String, String[]> chartData = new LinkedHashMap<>(2);
        List<String> xAxisData = new ArrayList<>();
        List<String> yAxisData = new ArrayList<>();

        Random rand = new Random();
        for (int i = 10; i > 0; i--) {
            xAxisData.add(getPastDate(i));

            int randPrice = rand.nextInt(300) + 20;
            yAxisData.add(String.valueOf(randPrice));
        }

        chartData.put("xAxisData", xAxisData.toArray(new String[10]));
        chartData.put("yAxisData", yAxisData.toArray(new String[10]));
        return chartData;
    }

    /**
     * 获取发行人首页的图表数据
     *
     * @return map
     */
    @Override
    public Map<String, String[]> getPublishChartData() {
        Map<String, String[]> chartData = new LinkedHashMap<>(2);
        List<String> xAxisData = new ArrayList<>();
        List<String> yAxisData = new ArrayList<>();

        Random rand = new Random();
        for (int i = 10; i > 0; i--) {
            xAxisData.add(getPastDate(i));

            int randPrice = rand.nextInt(300) + 20;
            yAxisData.add(String.valueOf(randPrice));
        }

        chartData.put("xAxisData", xAxisData.toArray(new String[10]));
        chartData.put("yAxisData", yAxisData.toArray(new String[10]));
        return chartData;
    }

    /**
     * 获取审核人首页的图表数据
     *
     * @return map
     */
    @Override
    public Map<String, String[]> getOperateChartData() throws ParseException {
        Map<String, String[]> chartData = new LinkedHashMap<>(2);
        List<String> xAxisData = new ArrayList<>();
        List<String> yAxisInvest = new ArrayList<>();
        List<String> yAxisDataPublish = new ArrayList<>();

        Random rand = new Random();
        for (int i = 10; i > 0; i--) {

            String days = getPastDate(i);
            xAxisData.add(days);

            SysUser sysUserQuery = new SysUser();
            Map<String, Object> params = new HashMap<>();
            params.put("endTime", days);
            sysUserQuery.setParams(params);
            List<SysUser> sysUserList = iSysUserService.selectUserList(sysUserQuery);

            AtomicReference<Long> publisherCount = new AtomicReference<>(0L);
            AtomicReference<Long> investorCount = new AtomicReference<>(0L);
            if (sysUserList.size() > 0) {
                sysUserList.forEach(sysUser -> {
                    List<SysRole> roles = iSysRoleService.selectRolesByUserId(sysUser.getUserId());
                    if (roles.size() > 0) {
                        roles.forEach(r -> {
                            if ("publish".equals(r.getRoleKey())) {
                                publisherCount.updateAndGet(v -> v + 1);
                            } else if ("invest".equals(r.getRoleKey())) {
                                investorCount.updateAndGet(v -> v + 1);
                            }
                        });
                    }
                });
            }
            yAxisDataPublish.add(String.valueOf(publisherCount.get()));
            yAxisInvest.add(String.valueOf(investorCount.get()));
        }

        chartData.put("yAxisInvest", yAxisInvest.toArray(new String[10]));
        chartData.put("yAxisDataPublish", yAxisDataPublish.toArray(new String[10]));
        chartData.put("xAxisData", xAxisData.toArray(new String[10]));
        return chartData;
    }


    /**
     * 获取过去第几天的日期
     *
     * @param past 第几天
     * @return 日期
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 获取首页的股票排名
     *
     * @return list
     */
    @Override
    public List<Stock> getStockRankTop10() {
        return stockMapper.selectStockRankTop10List(new Stock());
    }

    /**
     * 获取首页的股票排名
     *
     * @return list
     */
    @Override
    public List<Stock> getStockRankTop10(Long userId) {
        return stockMapper.selectStockRankTop10ListByHolder(userId);
    }
}
